//
//  ViewController.swift
//  Chapter 11 Currency Converter
//
//  Created by kinds on 2016/9/22.
//  Copyright © 2016年 hopy. All rights reserved.
//

import UIKit

class ViewController: UIViewController ,UITextFieldDelegate{
	
	let currencies = ["AUD","BGN","BRL","CAD","CHF",
	                  "CNY","CZK","DKK","EUR","GBP","HKD",
	                  "HRK","HUF","IDR","ILS","INR","JPY","KRW",
	                  "MXN","MYR","NOK","NZD","PHP","PLN","RON",
	                  "RUB","SEK","SGD","THB","TRY","USD","ZAR"]
	let baseurl = "http://api.fixer.io/latest"
	var fromCurrency = "USD"
	var toCurrency = "EUR"
	
	@IBOutlet weak var fromButton: UIButton!

	@IBOutlet weak var toButton: UIButton!
	@IBOutlet weak var amountTextField: UITextField!
	@IBOutlet weak var dateLabel: UILabel!
	@IBOutlet weak var rateLabel: UILabel!
	@IBOutlet weak var totalLabel: UILabel!
	@IBOutlet weak var flagImage: UIImageView!
	
	func textFieldShouldReturn(_ textField: UITextField) -> Bool {
		touchUp(view as! UIControl)
		return true
	}
	
	@IBAction func touchUp(_ sender: UIControl) {
		amountTextField.resignFirstResponder()
		setup()
	}
	
	@IBAction func chooseCurrency(_ sender: UIButton) {
		let alert = UIAlertController(title: NSLocalizedString("Choose Currency", comment: ""), message: nil, preferredStyle: .actionSheet)
		let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel){(action) in }
		alert.addAction(cancelAction)
		for currency in currencies{
			let action = UIAlertAction(title: currency, style: .default){(action) in
				if sender == self.fromButton{
					self.fromCurrency = action.title!
				}else{
					self.toCurrency = action.title!
				}
				self.setup()
			}
			alert.addAction(action)
		}
		
		present(alert, animated: true, completion: nil)
	}
	
	private func alert(title:String,message:String){
		let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
		let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
		alert.addAction(action)
		present(alert, animated: true, completion: nil)
	}
	
	private func setup(){
		fromButton.setTitle(fromCurrency, for: .normal)
		toButton.setTitle(toCurrency, for: .normal)
		
		var ratio:Double?
		if fromCurrency == toCurrency{
			ratio = 1.0
		}
		
		let session = URLSession.shared
		let url = URL(string: "\(baseurl)?base=\(fromCurrency)&symbols=\(toCurrency)")!
		print("GET URL:\(url.absoluteString)")
		session.dataTask(with: url) {(data,response,error)->Void in
			var json:[String:AnyObject] = [:]
			do{
				if let data = data{
					json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
				}
			}catch{
				self.alert(title: "Error", message: "Error parsing JSON")
			}
			
			let dateComponentsArray = (json["date"] as! String).components(separatedBy: "-")
			var dateComponents = DateComponents()
			dateComponents.year = Int(dateComponentsArray[0])!
			dateComponents.month = Int(dateComponentsArray[1])!
			dateComponents.day = Int(dateComponentsArray[2])!
			let date = Calendar.current.date(from: dateComponents)
			
			let rates = json["rates"] as! [String:Double]
			//let ratio = rates[self.toCurrency]
			
			if ratio == nil{
				ratio = rates[self.toCurrency]
			}
			
			let amount = self.amountTextField.text == "" ? 1.0:Double(self.amountTextField.text!)!
			
			OperationQueue.main.addOperation {
				let dateFormatter = DateFormatter()
				dateFormatter.dateStyle = .long
				self.dateLabel.text = dateFormatter.string(from: date!)
				
				let currencyFormatter = NumberFormatter()
				currencyFormatter.currencyCode = self.toCurrency
				currencyFormatter.numberStyle = .currency
				self.rateLabel.text = String(format: NSLocalizedString("Rate", comment: ""), currencyFormatter.string(from: NSNumber(value: ratio!))!)
				let total = amount * ratio!
				self.totalLabel.text = String(format: NSLocalizedString("Total", comment: ""), currencyFormatter.string(from: NSNumber(value:total))!)
			}
		}.resume()
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
		flagImage.image = UIImage(named: NSLocalizedString("flagicon", comment: ""))
		setup()
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}


}

